package com.defense;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewStudent {
    JFrame jf = new JFrame("新建学生");
    final int width = 500;
    final int height = 300;

    // 用于存储从文件读取的小组名称列表
    private List<String> groupNames = new ArrayList<>();

    // 学号输入框
    private JTextField uField;
    // 组长输入框
    private JTextField pField;
    // 小组下拉框
    private JComboBox<String> groupComboBox;

    // 用于存储小组与学生信息的映射关系
    private Map<String, Map<String, String>> groupStudentMap = new HashMap<>();

    // 组装视图
    public void init() {

        jf.setBounds((Toolkit.getDefaultToolkit().getScreenSize().width - width) / 2,
                (Toolkit.getDefaultToolkit().getScreenSize().height - height) / 2,
                width, height);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 窗口默认关闭

        jf.setLayout(new BorderLayout());

        JLabel titleLabel = new JLabel("新增学生", SwingConstants.CENTER);
        jf.add(titleLabel, BorderLayout.NORTH); // 将标题标签添加到JFrame的北部区域

        readGroupNamesFromFile();

        // 创建小组下拉框
        groupComboBox = new JComboBox<>(groupNames.toArray(new String[0]));

        // 创建垂直布局的Box
        Box vBox = Box.createVerticalBox();

        // 将小组下拉框添加到垂直Box中
        vBox.add(Box.createVerticalStrut(20));
        vBox.add(groupComboBox);
        vBox.add(Box.createVerticalStrut(20));

        // 用户名
        Box uBox = Box.createHorizontalBox();
        JLabel uLabel = new JLabel("学号：");
        uField = new JTextField(5);
        uBox.add(uLabel);
        uBox.add(Box.createHorizontalStrut(5));
        uBox.add(uField);

        // 组长输入框
        Box pBox = Box.createHorizontalBox();
        JLabel pLabel = new JLabel("组长：");
        pField = new JTextField(2);
        pBox.add(pLabel);
        pBox.add(Box.createHorizontalStrut(2));
        pBox.add(pField);

        // 按钮
        Box btnBox = Box.createHorizontalBox();
        JButton loginBtn = new JButton("新增");
        JButton cancelBtn = new JButton("返回");
        btnBox.add(loginBtn);
        btnBox.add(Box.createHorizontalStrut(20));
        btnBox.add(cancelBtn);

        // 为新增按钮添加事件监听器
        loginBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                String id = uField.getText();

                String name = pField.getText();
                // 获取下拉框选择的小组名
                String selectedGroup = (String) groupComboBox.getSelectedItem();

                // 将学生信息添加到对应的小组映射关系中
                addStudentToGroup(selectedGroup, id, name);

                saveStudentDataToFiles(id, name);

                JOptionPane.showMessageDialog(jf, "学生信息新增成功！");
            }
        });

        // 为返回按钮添加事件监听器
        cancelBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MangerInterface mangerInterface = new MangerInterface();
                mangerInterface.init();
                jf.setVisible(false);
                jf.dispose();
            }
        });

        // 将各组件添加到垂直Box中
        vBox.add(Box.createVerticalStrut(40));
        vBox.add(uBox);
        vBox.add(Box.createVerticalStrut(40));
        vBox.add(pBox);
        vBox.add(Box.createVerticalStrut(40));
        vBox.add(btnBox);

        jf.add(vBox, BorderLayout.CENTER);

        // 显示窗口
        jf.setVisible(true);
    }

    // 从文件读取小组名称数据的方法
    private void readGroupNamesFromFile() {
        try (BufferedReader reader = new BufferedReader(new FileReader("groups.txt"))) {
            String line;
            while ((line = reader.readLine())!= null) {
                groupNames.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 学生信息添加到小组映射关系
    private void addStudentToGroup(String group, String id, String name) {
        Map<String, String> studentMap = groupStudentMap.getOrDefault(group, new HashMap<>());
        studentMap.put(id, name);
        groupStudentMap.put(group, studentMap);
    }

    // 学号和组长信息关联保存到文件
    private void saveStudentDataToFiles(String id, String name) {
        try (FileWriter idWriter = new FileWriter("id.txt", true);
             FileWriter nameWriter = new FileWriter("names.txt", true)) {
            idWriter.write(id + "\n");
            nameWriter.write(name + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //学号获取组长信息
    public String getGroupNameByStudentId(String studentId) {
        for (Map.Entry<String, Map<String, String>> entry : groupStudentMap.entrySet()) {
            Map<String, String> studentMap = entry.getValue();
            if (studentMap.containsKey(studentId)) {
                return entry.getKey();
            }
        }
        return null;
    }

    // 小组名和学号获取组长信息
    public String getLeaderNameByGroupAndId(String group, String studentId) {
        Map<String, String> studentMap = groupStudentMap.getOrDefault(group, new HashMap<>());
        return studentMap.getOrDefault(studentId, null);
    }

    public static void main(String[] args) {
        NewStudent newStudent = new NewStudent();
        newStudent.init();
    }
}